import React, { Component } from 'react';
import { Modal, Tag, Radio, Button, Input, Form, Checkbox, message } from 'antd'
import ProductModal from '../../../components/Coupon/ProductModal/index'
import SelectProductModal from '../../../components/Coupon/SelectProductModal'
import './index.css'
import commonFuc from '../../../utils/commonFuc'

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
class EditCouponModal extends Component {   
    state = {
      countLimit:null,
      productIds:[],
      num:null,
      productList:[],
      productCheckNum:false,
      modalData:{
        visible: false
      },      
    }


    componentWillReceiveProps(newProps){   
      this.setState({
        productList: newProps.couponProductList,//只有产品列表为空的时候时候，才触发赋值
        num:newProps.form.getFieldValue('state.countLimit')===0?"0":"1",
      })   
    }    


    //触发搜索
    handleEditOk = () => {            
      const state = this.state;
      const form = this.props.form;
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if(!form.getFieldValue('productCheckNum') && state.productList.length == 0){
            message.error('请选择产品');
          }else{
            let _array = [];
            if(state.productList.length>0 && state.productIds[0] != -1){
              state.productList.forEach(item => {
                _array.push(item.id)
              });
            }
            
            this.props.handleOk({
              countLimit:form.getFieldValue('state.countLimit'),
              productIds:_array.length>0?_array:[-1]
            })
          }
        }
      })
    }
    handleEditCancel = () => {
        this.props.handleCancel();
        this.props.form.resetFields();
    }       
    showModal = () => {
      //如果是选了全部产品，则不可以弹出选择产品弹窗      
      if(this.state.productList.length === 0){
        message.error('产品范围为全部产品的优惠券不可以进行选择产品操作');
      }else{
        this.setState({
          modalData:{
            visible: true
          }
        });
      }
    }  
    handleProductOk = (data) => {
      let _array = [];
      if(data.length>0){       
        //过滤重复添加的产品 
        data.forEach(item1 => {          
          let _isNew = this.state.productList.some((item2) => (item1.id == item2.id));

          if(!_isNew){
            _array.push({
              id:item1.id,
              name:item1.name
            })
          }
        });        
      }      
      this.setState({
        modalData:{
          visible: false
        },
        productList:[...this.state.productList,..._array]
      });
    }
    handleProductCancel = () => {
      this.setState({
        modalData:{
          visible: false
        }
      });
    } 


    onAllProductChange = (e) =>{
      //点击‘全部产品’
      let _productIds = [];
      if(e.target.checked){
        _productIds = [-1];
      }else if(this.state.productList.length > 0){
        this.state.productList.forEach(element => {
          _productIds.push(element.id);
        });
      }
         
      this.setState({
        productIds:_productIds
      })    
    }    

    // 校验发行数量
    countLimitValidator = (rule, value, callback) => {
      const { num } = this.state;

      if(num == "1" && (!value || value > 5000 || value < 1 || !/^[0-9]*$/.test(value))){
        callback('输入发放数量，1-5000'); 
        return;
      }
      callback();
      
    }    
    render() {
          const { getFieldDecorator} = this.props.form;
          const state = this.state;
          const formItemLayout = {
            labelCol: {
              xs: { span: 27 },
              sm: { span: 3 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 14 },
            },
          };          
          return (
            <div>
                  <Modal title="编辑优惠券" style={{ height:700 }} width={800} visible={this.props.modalData.visible}
                  wrapClassName="vertical-center-modal"
                  onOk={this.handleEditOk} onCancel={this.handleEditCancel}
                  afterClose = {this.handleEditCancel}
                  >   
                  <Form onSubmit={this.handleSubmit}>
                      <FormItem
                        {...formItemLayout}
                        label="发行数量"
                      >
                        <RadioGroup value={ state.num } onChange={(e)=>{                          
                          this.setState({
                            num:e.target.value
                          });
                          this.props.form.setFieldsValue({
                            "state.countLimit":e.target.value === "1"?null:0
                          })
                        }}>
                          <Radio value="1">
                            <span>限量</span>
                            {getFieldDecorator('state.countLimit',{
                              rules:[{
                                validator: this.countLimitValidator,
                              }],
                              initialValue: this.props.modalData.countLimit
                              })(
                              <Input disabled={ state.num === "0"?true:false } placeholder=" 输入发放数量，1-5000" style={{ width: 200,marginLeft:10 }}/>                              
                            )}
                          </Radio>
                          <Radio value="0">不限量</Radio>
                        </RadioGroup>
                      </FormItem>    
                      <FormItem
                        {...formItemLayout}
                        label="适用范围"
                      >
                          <div style={{ whiteSpace: "initial" }}>
                            <div>
                              <Button type="primary" className="mr10"  onClick={this.showModal}>选择产品</Button>
                              <span className="color-red">优惠券创建后，指定产品只能添加，不能删除</span>
                            </div>
                            <div>
                              {
                                state.productList.map((item,index)=>(
                                  <Tag key={ index }>{ item.name }</Tag>
                                ))
                              }
                            </div>
                            {getFieldDecorator('productCheckNum',{
                              valuePropName: 'checked',              
                              initialValue:state.productList.length>0?false:true
                            })(                            
                              <Checkbox  onChange={this.onAllProductChange}>全部产品</Checkbox>
                            )}                            
                          </div>                        
                      </FormItem>                                           
                  </Form>
                </Modal>              
                {/* 选择产品弹窗 */}
                <SelectProductModal
                  modalData={state.modalData}
                  onOk={this.handleProductOk.bind(this)}
                  onCancel={this.handleProductCancel.bind(this)}
                ></SelectProductModal>
                {/* <ProductModal 
                  businessLevelSelect={ this.props.businessLevelSelect }
                  productList={ this.props.productList }
                  productListTotal={ this.props.productListTotal }
                  onCheckProduct={ (data)=> {this.props.onCheckProduct(data)} } 
                  modalData={state.modalData} 
                  handleOk={this.handleProductOk.bind(this)} 
                  handleCancel={this.handleProductCancel.bind(this)}/> */}
            </div>
        )
    }
}
export default Form.create({})(EditCouponModal);